package ssm.jdbc;

import java.sql.*;

public class JdbcTest {

    public static void main(String[] args){

        //创建连接
        Connection connection = null;
        //预编译的statement，使用预编译的statement提高性能
        PreparedStatement preparedStatement = null;
        //结果集
        ResultSet resultSet = null;

        try{
            //加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //通过驱动管理数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis_out?serverTimezone=Asia/Shanghai&characterEncoding=utf-8","root","123456");
            //定义SQL语句
            String sql="select * from user WHERE name = ?";
            //获取预处理statement
            preparedStatement = connection.prepareStatement(sql);
            //设置参数
            preparedStatement.setString(1,"zmy");
            //发出查询
            resultSet = preparedStatement.executeQuery();
            //遍历查询结果集
            while(resultSet.next()){
                System.out.println(resultSet.getString("id")+" "+resultSet.getString("name"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //当遍历结果集不为空时，挂壁遍历结果集
            if(resultSet!=null){
                try{
                    resultSet.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }

    }
}
